package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Bed;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.utils.CodeGenerator1;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Optional;

/**
 * 入住Service业务层处理
 *
 * @author yiYi
 * @date 2025-05-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1 判断老人是否入住 身份证号存在 而且 状态要为1 启用 2 4
        Elder elderDto = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()));
        if (ObjectUtil.isNotEmpty(elderDto)) {
            if (elderDto.getStatus() == 1 || elderDto.getStatus() == 2 || elderDto.getStatus() == 4)
                throw new RuntimeException("该老人已经存在");
        }

        //2 更新床位状态
        Long bedId = dto.getCheckInConfigDto().getBedId();
        //数据库的行锁 解决多线程资源竞争问题
        int count = bedMapper.updateBedStatus(bedId);
        if (count == 0) {
            throw new RuntimeException("该床位已被占用");
        }

        //3 新增或更新老人
        Elder elder =  addUpdateElder(dto, bedId, elderDto);
        //4 新增签约办理
        addContract(dto, elder);
        //5 新增入住信息
        CheckIn  checkIn = addCheckIn(dto, elder);
        //6 新增入住配置
        addCheckInConfig(dto, checkIn);
    }

    //6 新增入住配置
    private void addCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    //5 新增入住信息
    private CheckIn addCheckIn(CheckInApplyDto dto, Elder elderDto) {
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elderDto.getId());
        checkIn.setElderName(elderDto.getName());
        checkIn.setIdCardNo(elderDto.getIdCardNo());
        checkIn.setBedNumber(elderDto.getBedNumber());
        checkIn.setStatus(0);
        //备注 联系人
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        save(checkIn);

        return checkIn;
    }

    //4 新增签约办理
    private void addContract(CheckInApplyDto dto, Elder elderDto) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elderDto.getId().intValue());
        contract.setElderName(elderDto.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        LocalDateTime now = LocalDateTime.now();
        //判断合同是否过期
        if (now.isAfter(contract.getEndDate())) {
            throw new RuntimeException("合同已过期");
        }
        //状态根据时间改变
        if (now.isBefore(contract.getStartDate())) {
            contract.setStatus(0);
        } else if (now.isAfter(contract.getStartDate()) && now.isBefore(contract.getEndDate())) {
            contract.setStatus(1);
        } else {
            contract.setStatus(2);
        }
        contract.setContractNumber(CodeGenerator1.generateContractNumber());
        contractMapper.insert(contract);
    }

    //3新增或更新老人
    private Elder addUpdateElder(CheckInApplyDto dto, Long bedId, Elder elderDto) {
        Elder elder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        elder.setBedId(bedId);
        elder.setStatus(1);
        elder.setBedNumber(bedMapper.selectBedById(bedId).getBedNumber());
        if (ObjectUtil.isEmpty(elderDto)) {
            elderMapper.insert(elder);
        } else {
            elder.setId(elderDto.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = getById(id);
        //老人信息
        Optional.ofNullable(elderMapper.selectById(checkIn.getElderId()))
                .ifPresent(e -> {
                    CheckInElderVo elderVo = BeanUtil.toBean(e, CheckInElderVo.class);
                    //  设置年龄
                    int age = IdcardUtil.getAgeByIdCard(e.getIdCardNo());
                    elderVo.setAge(age);
                    vo.setCheckInElderVo(elderVo);
                });
        //家属信息
        String jsonString = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(jsonString, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVoList);
        //入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(
                new LambdaQueryWrapper<CheckInConfig>()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));

        if (ObjectUtil.isEmpty(checkInConfig)){
            throw new RuntimeException("入住配置信息不存在");
        }

        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        // 开始日期与结束日期
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);
        //合同信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));
        vo.setContract(contract);
        return vo;
    }
}
